﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace SLNavigationFrameworkEx
{
    public static class UriHelper
    {
        #region Public Method GetParamListByUriPattern

        public static IList<string> GetParamListByUriPattern(string uriPattern)
        {
            string pattern = @"(\{[A-Za-z0-9]+\})";
            var regex = new Regex(pattern);

            var result = new List<string>();

            MatchCollection mc = regex.Matches(uriPattern);

            foreach (Match item in mc)
            {
                result.Add(item.Value);
            }

            return result;
        }

        #endregion

        #region Public Method Convert2UriByUriPattern

        public static Uri Convert2UriByUriPattern(List<object> firstValueList, string uriPattern, List<object> secondValueList)
        {
            Uri result = null;

            if (firstValueList.Count == 0 || string.IsNullOrEmpty(uriPattern))
            {
                return result;
            }

            var patternParamList = UriHelper.GetParamListByUriPattern(uriPattern);

            if (secondValueList != null)
            {
                for (var i = secondValueList.Count - 1; i >= 0; i--)
                {
                    firstValueList.Insert(0, secondValueList[i]);
                }
            }

            if (firstValueList.Count == patternParamList.Count)
            {
                for (var i = 0; i < patternParamList.Count; i++)
                {
                    uriPattern = uriPattern.Replace(patternParamList[i], System.Convert.ToString(firstValueList[i]));
                }
            }

            return new Uri(uriPattern, UriKind.RelativeOrAbsolute);
        }

        #endregion
    }
}
